package com.wwlwxg.spring_security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.accept.ParameterContentNegotiationStrategy;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class AdminWebConfig implements WebMvcConfigurer {

  // 自定义内容协商策略
  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    Map<String, MediaType> map = new HashMap<>();
    map.put("json", MediaType.APPLICATION_JSON);
    map.put("xml", MediaType.APPLICATION_XML);
    map.put("diy", MediaType.parseMediaType("application/x-diy"));
    // 指定支持解析哪些参数对应的哪些媒体类型
    ParameterContentNegotiationStrategy strategy = new ParameterContentNegotiationStrategy(map);
    HeaderContentNegotiationStrategy headerStrategy = new HeaderContentNegotiationStrategy();

    configurer.strategies(Arrays.asList(strategy, headerStrategy));
  }

  /**
   * 增加自定义的协议数据
   * 属性1;属性2;
   * @param converters
   */
  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new DiyMessageConverter());
  }

  @Override
  public void configurePathMatch(PathMatchConfigurer configurer) {
    UrlPathHelper helper = new UrlPathHelper();
    // 不移除 分号 后面的内容，矩阵变量的内容就可以生效
    helper.setRemoveSemicolonContent(false);

  }

  /**
   * 增加参数转换器
   * 将前端传递过来的字符串转换为Pet对象，传入参数中
   * @param registry
   */
  @Override
  public void addFormatters(FormatterRegistry registry) {
    registry.addConverter(new Converter<String, Pet>() {
      @Override
      public Pet convert(String s) {
        if(StringUtils.isEmpty(s)) {
          return null;
        }
        String[] split = s.split(",");
        Pet pet = new Pet();
        pet.setId(Integer.parseInt(split[0]));
        pet.setName(split[1]);
        return pet;
      }
    });
  }
}
